package com.umbacos.udm.client.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.umbacos.udm.client.arch.Popup;
import com.umbacos.udm.client.arch.Popup.uPopupHandler;
import com.umbacos.udm.client.model.Presenter;
import com.umbacos.udm.client.model.Transmission;
import com.umbacos.udm.client.model.UdmStatus;
import com.umbacos.udm.client.model.View;
import com.umbacos.udm.client.model.Transmission.TransSubscriber;
import com.umbacos.udm.client.view.TransmissionView;

public class TransmissionPresenter implements Presenter, TransSubscriber {

	private TransmissionView tv;
	private final Transmission t=new Transmission();
	
	public void bind(final View mv, final UdmStatus us) {

		final TransmissionPresenter tp = this;
		tv = new TransmissionView();
		mv.add(tv);

		tv.btConnect.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				HTML htContent=new HTML("NB: to address a bug in Transmission Settings management, Transmission will be now killed and restarted.<BR>The main effect will be the unavailability of Transmission built-in web client until you disconnect");
				final Popup pp0=new Popup("Start Transmission monitor", htContent, Popup.POPUP_CANCEL + Popup.POPUP_OK);
				pp0.showPopup();
				pp0.addEventHandler(new uPopupHandler() {
					
					@Override
					public void okClickCallback(Popup pp) {
						t.addSubscription(tp);
						t.init(new RequestCallback() {
							
							@Override
							public void onResponseReceived(Request request, Response response) {
								if (response.getStatusCode()==200) {
										t.update();
										pp0.hide();
								} else {
									Popup pp=new Popup("Transmission Error", new Label(response.getText()), Popup.POPUP_CLOSE);
									pp.showPopup();
								}
								
							}
							
							@Override
							public void onError(Request request, Throwable exception) {
								Popup pp=new Popup("Transmission Error", new Label(exception.getMessage()), Popup.POPUP_CLOSE);
								pp.showPopup();				
							}
						});		
					}
				});
			}
		});
	}

	@Override
	public void update() {
		Popup pp=new Popup("Transmission Error", new Label("ciaciao"), Popup.POPUP_CLOSE);
		pp.showPopup();				
	}
}
